package com.party.admin.biz.notify;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.party.common.constant.Constant;
import com.party.common.utils.StringUtils;
import com.party.core.dao.read.member.MemberExternalAppReadDao;
import com.party.core.dao.read.wechat.WechatTemplateMassageReadDao;
import com.party.core.dao.read.wechatPlatform.WechatOpenMemberReadDao;
import com.party.core.dao.write.wechat.WechatTemplateMassageWriteDao;
import com.party.core.model.member.MemberExternalApp;
import com.party.core.model.member.MemberMerchant;
import com.party.core.model.notify.RelationWithChannel;
import com.party.core.model.wechat.WechatTemplateMassage;
import com.party.core.model.wechat.WechatTemplateMessageWithEvent;
import com.party.core.service.member.IMemberMerchantService;
import com.party.core.service.notify.IEventChannelService;
import com.party.core.service.wechat.IWechatTemplateMassageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 微信模板消息
 * Created by wei.li
 *
 * @date 2017/5/19 0019
 * @time 17:08
 */

@Service
public class WechatTemplateMessageBizService {

    private static Logger log = LoggerFactory.getLogger(WechatTemplateMessageBizService.class);

    @Autowired
    private IEventChannelService eventChannelService;

    @Autowired
    private IWechatTemplateMassageService wechatTemplateMassageService;

    @Autowired
    private WechatTemplateMassageReadDao wechatTemplateMassageReadDao;

    @Autowired
    private WechatTemplateMassageWriteDao wechatTemplateMassageWriteDao;

    @Autowired
    private IMemberMerchantService memberMerchantService;

    @Autowired
    private MemberExternalAppReadDao memberExternalAppReadDao;

    @Autowired
    private WechatOpenMemberReadDao wechatOpenMemberReadDao;

    /**
     * 我可以选择的事件
     *
     * @return 事件列表
     */
    public List<RelationWithChannel> myEventList(){

        //所有的微信通道事件
        List<RelationWithChannel> list = eventChannelService.wechatList(true);

        //排除已经添加的
        Map<String, Object> params = Maps.newHashMap();
        this.appendParams(params);
        List<WechatTemplateMessageWithEvent> wechatTemplateMassages
                = wechatTemplateMassageService.withEventList(new WechatTemplateMessageWithEvent(), params, null);

        List<RelationWithChannel> removeList = Lists.newArrayList();
       for (RelationWithChannel relationWithChannel : list){
            for (WechatTemplateMessageWithEvent w : wechatTemplateMassages){
                if (relationWithChannel.getId().equals(w.getEventChannelId())){
                    removeList.add(relationWithChannel);
                }
            }
        }

        list.removeAll(removeList);
        return list;
    }

    /**
     * 我可以选择的事件
     *
     * @param id 消息编号
     * @return 事件列表
     */
    public List<RelationWithChannel> myEventList(String id){

        //所有的微信通道事件
        List<RelationWithChannel> list = eventChannelService.wechatList(true);

        //排除已经添加的
        Map<String, Object> params = Maps.newHashMap();
        this.appendParams(params);
        List<WechatTemplateMessageWithEvent> wechatTemplateMassages
                = wechatTemplateMassageService.withEventList(new WechatTemplateMessageWithEvent(), params, null);

        List<RelationWithChannel> removeList = Lists.newArrayList();
        for (RelationWithChannel relationWithChannel : list){
            for (WechatTemplateMessageWithEvent w : wechatTemplateMassages){
                if (relationWithChannel.getId().equals(w.getEventChannelId()) && !w.getId().equals(id)){
                    removeList.add(relationWithChannel);
                }
            }
        }

        list.removeAll(removeList);
        return list;
    }

    /**
     * 初始化新加的app_id字段
     */
    public void init() {
        WechatTemplateMassage w = new WechatTemplateMassage();
        w.setType(Constant.WECHAT_ACCOUNT_TYPE_PARTNER);
        List<WechatTemplateMassage> wechatTemplateMassageList = wechatTemplateMassageReadDao.listPage(w, null);

        MemberMerchant m;
        MemberExternalApp ma;
        String appId = null;
        // 遍历消息模板
        for (WechatTemplateMassage template: wechatTemplateMassageList) {
            if (StringUtils.isEmpty(template.getMemberId())) {
                continue;
            }
            m = memberMerchantService.findByMemberId(template.getMemberId());
            if (null == m) {
                ma = memberExternalAppReadDao.findByMemberIdAndDeployType(template.getMemberId(), Constant.DEPLOY_TYPE_AUTH);
                if (null == ma) {
                    log.info("memberId = {}的用户, 在member_merchant和wechat_open_member里都没有数据", template.getMemberId());
                    continue;
                } else {
                    appId = wechatOpenMemberReadDao.get(ma.getExternalAccountId()).getAuthorizerAppid();
                }
            } else {
                appId = m.getOfficialAccountId();
            }
            template.setAppId(appId);
            wechatTemplateMassageWriteDao.update(template);
        }
    }

    /**
     * 追加查询参数
     * @param params
     */
    public void appendParams(Map<String, Object> params) {
        Set<String> types = Sets.newHashSet();
        types.add(Constant.WECHAT_ACCOUNT_TYPE_SYSTEM); // 公众号
        types.add(Constant.WECHAT_TEMPLATE_TYPE); // 小程序
        params.put("types", types);
    }
}
